//
//  MainItem.swift
//  ZJTools
//
//  Created by 万孟超 on 2023/10/19.
//

import Cocoa

class MainItem: NSView {
    
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }
    
    var selectAction: (() -> ())?
    
    lazy var contentLabel: NSTextField = {
        let titleLabel = NSTextField()
        titleLabel.isVerticalCenter = true
        titleLabel.font = .systemFont(ofSize: 14)
        titleLabel.isBordered = false
        titleLabel.isEditable = false
        titleLabel.isSelectable = false
        titleLabel.textColor = .black
        titleLabel.bezelStyle = .roundedBezel
        titleLabel.backgroundColor = .clear
        titleLabel.lineBreakMode = .byTruncatingTail
        return titleLabel
    }()
    
    lazy var iconImage: NSImageView = {
       let icon = NSImageView()
        return icon
    }()
    
    var itemModel: MainItemM? {
        didSet {
            if let itemModel = itemModel {
                contentLabel.stringValue = itemModel.title
                iconImage.image = NSImage(named: itemModel.image)
            }
        }
    }
    
    init() {
        super.init(frame: .zero)
        wantsLayer = true
        layer?.backgroundColor = NSColor.clear.cgColor
        installSubview()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func installSubview() {
        addSubview(iconImage)
        iconImage.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.centerY.equalToSuperview()
            make.size.equalTo(NSMakeSize(18, 18))
        }
        
        addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImage.snp.right).offset(10)
            make.centerY.equalToSuperview()
        }
    }
    
    override func mouseDown(with event: NSEvent) {
        if let itemModel = itemModel {
            itemModel.action()
            selectAction?()
        }
    }
}
